package fr.umlv.escapeir.gesture;

import java.awt.geom.Line2D;

public class Line implements Mask {
	
	private static final int MIN_SIZE = 20;
	private static final int STEEPNESS = 10;

	@Override
	public boolean isValid(Gesture g) {
		int nbElement = g.size();

		int xHead = g.getX(0);
		int xTail = g.getX(nbElement - 1);
		int yHead = g.getY(0);
		int yTail = g.getY(nbElement - 1);

		Line2D line = new Line2D.Double(xHead, yHead, xTail, yTail);

		double length = length(line);
		if(length < MIN_SIZE) return false;

		// Verify if the distance of all point of polyline (argument) is under 10
        for(int i = 0; i < nbElement; i++) {
                int x = g.getX(i);
                int y = g.getY(i);
                if(line.ptSegDist(x, y) >= STEEPNESS) return false;
        }

		// The Gesture g is a line
		Direction direction = Direction.UNDEFINED;

		if (Math.abs(xHead - xTail) < STEEPNESS) { // VERTICAL LINE 
			if(yHead < yTail) direction = Direction.DOWN;
			else direction = Direction.TOP;
		}
		else if(Math.abs(yHead - yTail) >= STEEPNESS && yHead > yTail) {
			if(xHead > xTail) direction = Direction.TOPLEFT;
			else direction = Direction.TOPRIGHT;
		}
		else if(Math.abs(yTail - yHead) < STEEPNESS) { // HORIZONTAL LINE
			if(xHead > xTail) direction = Direction.LEFT;
			else direction = Direction.RIGHT;
		}
		
		if (direction == Direction.UNDEFINED) return false;
		
		g.setGestureValid(Masks.LINE, direction, (int)length);
		return true;
	}
	
	private static double length(Line2D line) {

		double x1 = line.getX1();
		double y1 = line.getY1();
		double x2 = line.getX2();
		double y2 = line.getY2();

		return Math.sqrt( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
	}
}
